{% extends 'layout.html' %}
{% load static %}

{% block title %}超市收银系统{% endblock %}

{% block extra_head %}
<style>
    .receipt-scroll {
        scrollbar-width: thin;
        scrollbar-color: #6b7280 #e5e7eb;
    }
    .receipt-scroll::-webkit-scrollbar {
        width: 6px;
    }
    .receipt-scroll::-webkit-scrollbar-track {
        background: #e5e7eb;
    }
    .receipt-scroll::-webkit-scrollbar-thumb {
        background-color: #6b7280;
        border-radius: 3px;
    }
    .product-row:hover {
        background-color: #f3f4f6;
    }
    .product-image {
        height: 120px;
        object-fit: contain;
    }
    .category-btn {
        transition: all 0.2s;
    }
    .category-btn.active {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    .add-to-cart {
        opacity: 0;
        transition: opacity 0.2s;
    }
    .product-btn:hover .add-to-cart {
        opacity: 1;
    }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen flex">
    <!-- 商品展示区域 -->
    <div class="w-3/5 p-4">
        <div class="bg-white rounded-lg shadow-md p-4 h-full flex flex-col">
            <h1 class="text-2xl font-bold text-gray-800 mb-4">收银台 - 商品扫描</h1>
            
            <!-- 扫描输入框 -->
            <div class="flex mb-4">
                <input 
                    type="text" 
                    id="barcodeInput" 
                    placeholder="扫描条形码或输入商品编号" 
                    class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    autofocus
                >
                <button 
                    id="addProductBtn" 
                    class="bg-blue-600 text-white px-4 py-2 rounded-r-md hover:bg-blue-700 transition"
                >
                    添加商品
                </button>
            </div>
            
            <!-- 商品分类筛选 -->
            <div class="flex flex-wrap gap-2 mb-4" id="categoryFilters">
                <button class="category-btn px-3 py-1 rounded-md bg-gray-200 text-gray-800 active" data-category-id="all">
                    全部商品
                </button>
                {% for category in categories %}
                <button class="category-btn px-3 py-1 rounded-md bg-{{ category.color|default:'gray' }}-100 text-{{ category.color|default:'gray' }}-800" 
                        data-category-id="{{ category.id }}">
                    {{ category.name }}
                </button>
                {% endfor %}
            </div>
            
            <!-- 商品展示网格 -->
            <div class="grid grid-cols-4 gap-4 overflow-y-auto" id="productsGrid">
                {% for product in products %}
                <div class="product-btn bg-white border border-gray-200 rounded-lg p-3 hover:shadow-md transition flex flex-col" 
                     data-id="{{ product.product_code }}" 
                     data-category="{{ product.category.id }}">
                    <!-- 商品图片 -->
                    {% if product.image_url %}
                    <img src="{{ product.image_url }}" alt="{{ product.name }}" class="product-image mb-2">
                    {% else %}
                    <div class="product-image bg-gray-100 flex items-center justify-center mb-2">
                        <i class="fas fa-box-open text-gray-300 text-3xl"></i>
                    </div>
                    {% endif %}
                    
                    <!-- 商品信息 -->
                    <div class="flex-grow">
                        <div class="font-medium text-gray-800 truncate">{{ product.name }}</div>
                        <div class="text-sm text-gray-500 my-1">
                            售价: <span class="text-pink-600 font-semibold">¥{{ product.price }}</span>
                            {% if product.cost_price > product.price %}
                            <span class="text-xs text-gray-400 line-through ml-1">¥{{ product.cost_price }}</span>
                            {% endif %}
                        </div>
                        <div class="text-xs text-gray-400 flex justify-between items-end">
                            <span>{{ product.product_code }}</span>
                            <span class="bg-gray-100 px-2 py-1 rounded">{{ product.unit|default:"件" }}</span>
                        </div>
                    </div>
                    
                    <!-- 添加购物车按钮 -->
                    <button class="add-to-cart mt-2 bg-blue-500 text-white py-1 rounded hover:bg-blue-600 transition"
                            data-product-id="{{ product.product_code }}">
                        加入购物车
                    </button>
                    
                    <!-- 保质期提示 -->
                    {% if product.shelf_life_end_date %}
                    <div class="absolute top-2 left-2 bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded-full">
                        <i class="fas fa-clock mr-1"></i>
                        {{ product.shelf_life_end_date|date:"Y-m-d" }}
                    </div>
                    {% endif %}
                </div>
                {% empty %}
                <div class="col-span-4 text-center py-8 text-gray-500">
                    <i class="fas fa-box-open text-4xl mb-2"></i>
                    <p>暂无商品</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- 收银台右侧区域 -->
    <div class="w-2/5 p-4">
        <div class="bg-white rounded-lg shadow-md p-4 h-full flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">订单详情</h2>
                <div class="text-sm text-gray-500">收银员: {{ request.user.username|default:"未登录" }}</div>
            </div>
            
            <!-- 购物车清单 -->
            <div id="scannedProducts" class="receipt-scroll overflow-y-auto flex-1 mb-4 border rounded">
                <div class="grid grid-cols-12 gap-2 p-2 bg-gray-100 font-semibold text-gray-600 text-sm">
                    <div class="col-span-5">商品名称</div>
                    <div class="col-span-2 text-right">单价</div>
                    <div class="col-span-2 text-center">数量</div>
                    <div class="col-span-3 text-right">小计</div>
                </div>
                <div class="empty-cart-msg text-center text-gray-500 py-10">购物车为空，请添加商品</div>
                <!-- 商品列表将通过JS动态添加 -->
            </div>
            
            <!-- 订单汇总信息 -->
            <div class="bg-gray-100 p-4 rounded-md mb-4 text-sm">
                <div class="flex justify-between py-1">
                    <span class="text-gray-600">商品总数:</span>
                    <span id="totalQuantity" class="font-semibold">0</span>
                </div>
                <div class="flex justify-between py-1">
                    <span class="text-gray-600">总金额:</span>
                    <span id="totalAmount" class="font-semibold">¥0.00</span>
                </div>
                <div class="flex justify-between py-1">
                    <span class="text-gray-600">折扣合计:</span>
                    <span id="totalDiscount" class="font-semibold text-red-500">-¥0.00</span>
                </div>
                <div class="flex justify-between py-1 border-t border-gray-200 mt-2 pt-2">
                    <span class="text-gray-800 font-bold">应付金额:</span>
                    <span id="payableAmount" class="font-bold text-xl text-blue-600">¥0.00</span>
                </div>
            </div>
            
            <!-- 支付按钮 -->
            <div class="grid grid-cols-3 gap-3 mb-4">
                <button class="payment-method bg-green-100 hover:bg-green-200 text-green-800 py-3 rounded-md transition" data-type="cash">
                    <i class="fas fa-money-bill-wave text-xl mb-1"></i><br>
                    现金支付
                </button>
                <button class="payment-method bg-blue-100 hover:bg-blue-200 text-blue-800 py-3 rounded-md transition" data-type="card">
                    <i class="fas fa-credit-card text-xl mb-1"></i><br>
                    银行卡支付
                </button>
                <button class="payment-method bg-yellow-100 hover:bg-yellow-200 text-yellow-800 py-3 rounded-md transition" data-type="mobile">
                    <i class="fas fa-mobile-alt text-xl mb-1"></i><br>
                    手机支付
                </button>
            </div>
            
            <!-- 操作按钮 -->
            <div class="flex space-x-3">
                <button id="clearBtn" class="flex-1 bg-red-100 hover:bg-red-200 text-red-800 py-3 rounded-md transition">
                    清空购物车
                </button>
                <button id="checkoutBtn" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-md transition">
                    确认结算
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 小票弹窗 -->
<div id="receiptModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold">收据打印</h3>
            <button id="closeReceiptModal" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div id="receiptContent" class="border rounded p-4 mb-4"></div>
        <div class="flex justify-end space-x-3">
            <button id="printReceiptBtn" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
                <i class="fas fa-print mr-2"></i>打印
            </button>
            <button id="newOrderBtn" class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300">
                新订单
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 从Django模板中获取商品数据
    const products = {
        {% for product in products %}
        '{{ product.product_code }}': {
            id: '{{ product.product_code }}',
            name: '{{ product.name|escapejs }}',
            price: parseFloat('{{ product.price }}'),
            category: '{{ product.category.id }}',
            unit: '{{ product.unit|default:"件"|escapejs }}',
            barcode: '{{ product.product_code }}',
            image_url: '{% if product.image_url %}{{ product.image_url }}{% else %}{% static "img/default-product.png" %}{% endif %}',
            shelf_life: '{% if product.shelf_life_end_date %}{{ product.shelf_life_end_date|date:"Y-m-d" }}{% endif %}'
        },
        {% endfor %}
    };

    // 购物车数据
    let cart = {};
    let totalQuantity = 0;
    let totalAmount = 0;
    let totalDiscount = 0;
    let currentPaymentMethod = null;

    // DOM元素
    const barcodeInput = document.getElementById('barcodeInput');
    const addProductBtn = document.getElementById('addProductBtn');
    const productsGrid = document.getElementById('productsGrid');
    const scannedProducts = document.getElementById('scannedProducts');
    const emptyCartMsg = document.querySelector('.empty-cart-msg');
    const totalQuantityEl = document.getElementById('totalQuantity');
    const totalAmountEl = document.getElementById('totalAmount');
    const totalDiscountEl = document.getElementById('totalDiscount');
    const payableAmountEl = document.getElementById('payableAmount');
    const clearBtn = document.getElementById('clearBtn');
    const checkoutBtn = document.getElementById('checkoutBtn');
    const paymentBtns = document.querySelectorAll('.payment-method');
    const categoryBtns = document.querySelectorAll('.category-btn');
    const receiptModal = document.getElementById('receiptModal');
    const receiptContent = document.getElementById('receiptContent');
    const closeReceiptModal = document.getElementById('closeReceiptModal');
    const printReceiptBtn = document.getElementById('printReceiptBtn');
    const newOrderBtn = document.getElementById('newOrderBtn');

    // 初始化事件监听
    initEventListeners();

    function initEventListeners() {
        // 条形码扫描输入
        barcodeInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addProductByBarcode();
            }
        });
        
        addProductBtn.addEventListener('click', addProductByBarcode);

        // 商品按钮点击事件
        document.querySelectorAll('.add-to-cart').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const productId = this.dataset.productId;
                addProductToCart(productId);
            });
        });

        // 商品分类筛选
        categoryBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 更新活动状态
                categoryBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const categoryId = this.dataset.categoryId;
                filterProductsByCategory(categoryId);
            });
        });

        // 支付方式选择
        paymentBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                paymentBtns.forEach(b => b.classList.remove('border-2', 'border-blue-500'));
                this.classList.add('border-2', 'border-blue-500');
                currentPaymentMethod = this.dataset.type;
                
                // 更新结算按钮状态
                updateCheckoutButton();
            });
        });

        // 清空购物车
        clearBtn.addEventListener('click', clearCart);

        // 结算按钮
        checkoutBtn.addEventListener('click', processCheckout);

        // 收据弹窗
        closeReceiptModal.addEventListener('click', () => receiptModal.classList.add('hidden'));
        printReceiptBtn.addEventListener('click', printReceipt);
        newOrderBtn.addEventListener('click', startNewOrder);
    }

    // 通过条形码添加商品
    function addProductByBarcode() {
        const barcode = barcodeInput.value.trim();
        if (!barcode) return;
        
        // 查找商品
        let foundProduct = null;
        
        // 1. 通过商品编码查找
        if (products[barcode]) {
            foundProduct = products[barcode];
        }
        
        // 2. 或通过其他条形码字段查找（可根据实际需求扩展）
        
        if (foundProduct) {
            addProductToCart(foundProduct.id);
            barcodeInput.value = '';
            barcodeInput.focus();
        } else {
            showToast('未找到匹配的商品', 'error');
        }
    }

    // 添加商品到购物车
    function addProductToCart(productId) {
        if (!products[productId]) {
            showToast('商品不存在', 'error');
            return;
        }

        if (cart[productId]) {
            // 商品已在购物车中，增加数量
            cart[productId].quantity += 1;
            cart[productId].subtotal = cart[productId].price * cart[productId].quantity;
        } else {
            // 新商品添加到购物车
            cart[productId] = {
                ...products[productId],
                quantity: 1,
                discount: 0,
                subtotal: products[productId].price
            };
        }
        
        updateCartDisplay();
        showToast(`${products[productId].name} 已添加到购物车`, 'success');
    }

    // 更新购物车显示
    function updateCartDisplay() {
        // 计算汇总数据
        totalQuantity = 0;
        totalAmount = 0;
        totalDiscount = 0;
        
        // 生成购物车HTML
        let cartHtml = `
            <div class="grid grid-cols-12 gap-2 p-2 bg-gray-100 font-semibold text-gray-600 text-sm">
                <div class="col-span-5">商品名称</div>
                <div class="col-span-2 text-right">单价</div>
                <div class="col-span-2 text-center">数量</div>
                <div class="col-span-3 text-right">小计</div>
            </div>
        `;
        
        // 添加每个商品行
        for (const productId in cart) {
            const item = cart[productId];
            
            cartHtml += `
                <div class="product-row grid grid-cols-12 gap-2 p-2 border-b hover:bg-gray-50">
                    <div class="col-span-5 truncate">${item.name}</div>
                    <div class="col-span-2 text-right">¥${item.price.toFixed(2)}</div>
                    <div class="col-span-2 flex items-center justify-center space-x-2">
                        <button class="decrease-btn w-6 h-6 rounded bg-gray-200 hover:bg-gray-300" 
                                data-id="${productId}">-</button>
                        <span class="quantity">${item.quantity}</span>
                        <button class="increase-btn w-6 h-6 rounded bg-gray-200 hover:bg-gray-300" 
                                data-id="${productId}">+</button>
                    </div>
                    <div class="col-span-3 text-right">¥${item.subtotal.toFixed(2)}</div>
                </div>
            `;
            
            totalQuantity += item.quantity;
            totalAmount += item.subtotal;
        }
        
        // 更新DOM
        scannedProducts.innerHTML = cartHtml;
        emptyCartMsg.classList.add('hidden');
// emptyCartMsg.classList.add('hidden');
        
// 更新汇总信息
totalAmountEl.textContent = `¥${totalAmount.toFixed(2)}`;
totalQuantityEl.textContent = totalQuantity;
payableAmountEl.textContent = `¥${(totalAmount - totalDiscount).toFixed(2)}`;

// 添加数量按钮事件
document.querySelectorAll('.decrease-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const productId = this.dataset.id;
        decreaseQuantity(productId);
    });
});

document.querySelectorAll('.increase-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const productId = this.dataset.id;
        increaseQuantity(productId);
    });
});

// 更新结账按钮状态
updateCheckoutButton();
}

// 减少商品数量
function decreaseQuantity(productId) {
if (cart[productId].quantity > 1) {
    cart[productId].quantity -= 1;
    cart[productId].subtotal = cart[productId].price * cart[productId].quantity;
    updateCartDisplay();
} else {
    delete cart[productId];
    if (Object.keys(cart).length === 0) {
        clearCart();
    } else {
        updateCartDisplay();
    }
}
}

// 增加商品数量
function increaseQuantity(productId) {
cart[productId].quantity += 1;
cart[productId].subtotal = cart[productId].price * cart[productId].quantity;
updateCartDisplay();
}

// 清空购物车
function clearCart() {
if (confirm('确定要清空购物车吗？')) { 
    cart = {};
    totalQuantity = 0;
    totalAmount = 0;
    totalDiscount = 0;
    
    scannedProducts.innerHTML = '<div class="empty-cart-msg text-center text-gray-500 py-10">购物车为空，请添加商品</div>';
    emptyCartMsg.classList.remove('hidden');
    
    totalQuantityEl.textContent = '0';
    totalAmountEl.textContent = '¥0.00';
    totalDiscountEl.textContent = '-¥0.00';
    payableAmountEl.textContent = '¥0.00';
    
    // 重置支付方式
    paymentBtns.forEach(b => b.classList.remove('border-2', 'border-blue-500'));
    currentPaymentMethod = null;
    updateCheckoutButton();
    
    barcodeInput.focus();
}
}

// 更新结账按钮状态
function updateCheckoutButton() {
if (Object.keys(cart).length > 0 && currentPaymentMethod) {
    checkoutBtn.disabled = false;
    checkoutBtn.classList.remove('bg-gray-400', 'cursor-not-allowed');
    checkoutBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
} else {
    checkoutBtn.disabled = true;
    checkoutBtn.classList.add('bg-gray-400', 'cursor-not-allowed');
    checkoutBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
}
}

// 处理结账
function processCheckout() {
if (Object.keys(cart).length === 0) {
    showToast('购物车为空，无法结账', 'error');
    return;
}

if (!currentPaymentMethod) {
    showToast('请选择支付方式', 'error');
    return;
}

// 构建订单数据
const orderItems = Object.values(cart).map(item => ({
    product_id: item.id,
    name: item.name,
    quantity: item.quantity,
    price: item.price,
    subtotal: item.subtotal
}));

const orderData = {
    items: orderItems,
    total: totalAmount - totalDiscount,
    payment_method: currentPaymentMethod,
    csrfmiddlewaretoken: '{{ csrf_token }}'
};

// 模拟AJAX请求
fetch('{% url "checkout" %}', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': '{{ csrf_token }}'
    },
    body: JSON.stringify(orderData)
})
.then(response => response.json())
.then(data => {
    if (data.status === 'success') {
        showReceipt(data.order);
    } else {
        showToast(data.message || '结账失败', 'error');
    }
})
.catch(error => {
    console.error('Error:', error);
    showToast('结账过程中发生错误', 'error');
});
}

// 显示收据
function showReceipt(order) {
let receiptHtml = `
    <div class="text-center font-bold mb-2 text-lg">超市收据</div>
    <div class="text-center text-xs mb-4">${new Date().toLocaleString()}</div>
    <div class="text-center text-sm mb-4">
        <div>收银员: ${order.cashier || '{{ request.user.username|default:"系统" }}'}</div>
        <div>订单号: ${order.id}</div>
    </div>
    <div class="border-t border-b border-gray-300 py-1 mb-2">
        ${order.items.map(item => `
            <div class="flex justify-between mb-1">
                <div class="truncate flex-1">
                    ${item.name} 
                    <span class="text-xs text-gray-500">×${item.quantity}</span>
                </div>
                <div class="text-right ml-2">¥${(item.price * item.quantity).toFixed(2)}</div>
            </div>
        `).join('')}
    </div>
    <div class="border-b border-gray-300 pb-2 mb-2 text-sm">
        <div class="flex justify-between">
            <span>商品总数:</span>
            <span>${order.items.reduce((sum, item) => sum + item.quantity, 0)}</span>
        </div>
        <div class="flex justify-between">
            <span>合计:</span>
            <span>¥${order.total.toFixed(2)}</span>
        </div>
        <div class="flex justify-between">
            <span>支付方式:</span>
            <span>${getPaymentMethodName(order.payment_method)}</span>
        </div>
    </div>
    <div class="text-center text-xs mt-4">
        <div>感谢您的惠顾</div>
        <div>欢迎再次光临</div>
    </div>
`;

receiptContent.innerHTML = receiptHtml;
receiptModal.classList.remove('hidden');
}

// 打印收据
function printReceipt() {
const printWindow = window.open('', '_blank');
printWindow.document.write(`
    <html>
        <head>
            <title>收据打印</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; }
                .receipt { width: 80mm; margin: 0 auto; }
                .center { text-align: center; }
                .bold { font-weight: bold; }
                .border-bottom { border-bottom: 1px dashed #ccc; padding-bottom: 5px; margin-bottom: 5px; }
                .flex { display: flex; }
                .justify-between { justify-content: space-between; }
            </style>
        </head>
        <body>
            <div class="receipt">
                ${receiptContent.innerHTML.replace(/class="[^"]*"/g, '')}
            </div>
            <script>
                setTimeout(() => {
                    window.print();
                    window.close();
                }, 200);
            </script>
        </body>
    </html>
`);
printWindow.document.close();
}

// 开始新订单
function startNewOrder() {
clearCart();
receiptModal.classList.add('hidden');
barcodeInput.focus();
}

// 分类筛选商品
function filterProductsByCategory(categoryId) {
document.querySelectorAll('.product-btn').forEach(btn => {
    if (categoryId === 'all' || btn.dataset.category === categoryId) {
        btn.style.display = 'block';
    } else {
        btn.style.display = 'none';
    }
});
}

// 获取支付方式名称
function getPaymentMethodName(method) {
const methods = {
    'cash': '现金',
    'card': '银行卡',
    'mobile': '手机支付'
};
return methods[method] || method;
}

// 显示消息提示
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `fixed top-4 right-4 px-4 py-2 rounded-md shadow-lg text-white z-50 ${
    type === 'error' ? 'bg-red-500' : 
    type === 'success' ? 'bg-green-500' : 'bg-blue-500'
}`;
toast.textContent = message;
document.body.appendChild(toast);

setTimeout(() => {
    toast.classList.add('opacity-0', 'transition-opacity', 'duration-500');
    setTimeout(() => toast.remove(), 500);
}, 3000);
}
});
</script>
{% endblock %}
